<?php

require_once 'classes/LightPressPlugin.php';

class HighlightImage extends LightPressPlugin {
    
    var $constructor_args = array(
        'category'=>'category id from which to get the last post',
        'header'=>'header to use in the template');
    var $default_context = 255;
    var $description = 'Sets the last post\'s title and abstract from the given category in a box on the sidebar.';
    
    var $active = true;
    var $hooks = array('sidebar');
    
    var $category = '';
    var $header = '';
    
    function HighlightImage(&$frontend, $args, $dummy_run=false) {
        $this->LightPressPlugin($frontend, $args, $dummy_run);
    }
    
    function run($hook, &$payload) {
        $tpl =& $this->_frontend->tpl;
        $db =& $this->_frontend->db;
        $options =& $this->_frontend->options;
        $tables =& $this->_frontend->tables;
        
        $category_id = trim($this->category);
            
        if (empty($category_id))
                return $this->hide();
        
        $q = "SELECT
                id, post_name as name, post_title as title, post_content as content,
                UNIX_TIMESTAMP(p.post_date_gmt) + '" . $options['gmt_offset'] . "' as tstamp, 
                UNIX_TIMESTAMP(p.post_date_gmt) as tstamp_gmt, post_category
            FROM " . $tables['posts'] . " p
            INNER JOIN " . $tables['post2cat'] . " p2c on p.id=p2c.post_id
            WHERE
                p.post_date_gmt <= '" . $this->_frontend->where_date . "' AND
                (p.post_status='publish') AND p2c.category_id=$category_id
            ORDER BY
                p.post_date desc limit 1";
            
        if ($db->query($q) == 0)
             return $this->hide();
        
        $post = $db->next();
        
        $tpl_post = array('plugin_highlightimage_header'=>$this->header);
        
        $post['plugin_highlightimage_tstamp'] = (int)$post['tstamp'];
        $tpl_post['plugin_highlightimage_permalink'] = $this->_frontend->getPermalink($post['id'], $post['name'], $post['tstamp'], $post['post_category']);
        $tpl_post['plugin_highlightimage_short_date'] = strftime($options['short_date_format'], $post['tstamp']);
        $tpl_post['plugin_highlightimage_title'] = stripslashes($post['title']);
        $tpl_post['plugin_highlightimage_safe_title'] = htmlspecialchars($tpl_post['plugin_highlightimage_title'], ENT_QUOTES);
        
        $matches = array();
        if (!preg_match('/<img\s+src="([^"]+)/', $post['content'], $matches))
            return $this->hide();
        
        $tpl_post['plugin_highlightimage_image'] = $matches[1];
        
        $tpl->setVar($tpl_post);
        $tpl->setFile('plugin_highlightimage', 'plugins/highlight_image.xml');
        $tpl->parse('PLUGIN_HIGHLIGHTIMAGE', 'plugin_highlightimage');    
    }
}

?>